<template>
  <x-page>
    <x-filter @search="handleSearch" @reset="resetSearch">
      <x-filter-item :label="$t('system.application.id')">
        <el-input
          v-model="searchParams.clientId"
          :placeholder="$t('system.application.placeholderInputId')"
          clearable
        ></el-input>
      </x-filter-item>
      <x-filter-item :label="$t('system.application.name')">
        <el-input
          v-model="searchParams.clientName"
          :placeholder="$t('system.application.placeholderInputName')"
          clearable
        ></el-input>
      </x-filter-item>
    </x-filter>
    <!--数据面板-->
    <x-data>
      <!--数据面板按钮插糟-->
      <template #tool>
        <el-row type="flex" class="tools" justify="space-between">
          <el-col :span="20">
            <el-button
              v-hasPermi="['oauth:client:add']"
              size="small"
              type="primary"
              :icon="buttonIcons('add')"
              @click="handleAdd"
            >
              {{ $t('system.application.add') }}</el-button
            >
          </el-col>
          <el-col :span="4" class="tools-config">
            <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
          </el-col>
        </el-row>
      </template>
      <!-- 数据表格 -->
      <x-table
        ref="tableCom"
        :pagination="pagination"
        :data-source="tableData"
        :loading="loading"
        :row-key="'id'"
        @on-change="handleTableChange"
        @on-selection-change="handleSelectionChange"
      >
        <el-table-column :label="$t('common.serialNumber')" :width="55" fixed type="index" />
        <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.prop"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
          :width="item.width"
          :min-width="item.minWidth || '-'"
          :label="item.label"
          :sortable="'custom'"
        >
          <template #default="scope">
            <el-switch
              v-if="item.prop === 'state'"
              :value="scope.row[item.prop]"
              active-color="#4474F6"
              inactive-color="#A5A9B2"
              @change="handleChangeState(scope.row[item.prop], scope.row.id)"
              :disabled="!checkBntPermi('oauth:client:state')"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
            <x-state-cell
              v-else-if="item.prop === 'autoapprove'"
              :stateClass="scope.row[item.prop] === 'false' ? 'gray' : scope.row[item.prop] ? 'success' : ''"
              :text="selectDictLabel(dictOptions['upms_registered_client.autoapprove'], scope.row[item.prop] + '')"
            />
            <el-image
              v-else-if="item.prop === 'clientImg' && scope.row[item.prop]"
              class="clientImg"
              fit="contain"
              :src="scope.row[item.prop]"
            />
            <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.opeartion')" :align="'center'" width="160">
          <template #default="scope">
            <more-table-actions
              :action-list="actions"
              :permis-list="permissionsActions"
              :row="scope.row"
              @onActionClick="handleActions"
            />
          </template>
        </el-table-column>
      </x-table>
    </x-data>
    <!-- 新增/编辑 -->
    <external-application-add
      ref="applicationAddCom"
      :dict-options="dictOptions"
      @handleSuccess="loadData"
    ></external-application-add>
    <!-- 重置密码 -->
    <external-reset-pwd ref="applicationPwdCom" @handleSuccess="loadData"></external-reset-pwd>
  </x-page>
</template>
<script>
  import { selectDictLabel, buttonIcons, TableListMixin, QueryDictMixin, PermissionsMixin } from '@package/utils'
  import ExternalApplicationAdd from '../components/externalApplicationAdd.vue'
  import ExternalResetPwd from '../components/externalResetPwd.vue'
  // import { TableListMixin, QueryDictMixin, PermissionsMixin } from '@/common/mixins/index.js'
  import { columns, actions } from '../config/externalApplication.js'
  import { listUrl, apiPutDeleteClient, apiPutEnableClient, apiPutDisableClient } from '../api/externalApplication.js'

  import { EnumApiCode } from '../../../../../../globalEnum.js'

  export default {
    name: 'ExternalApplication',
    components: { ExternalApplicationAdd, ExternalResetPwd },
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    data() {
      return {
        columns,
        listUrl,
        actions,
        loading: false,
        searchParams: {
          clientId: ''
        },
        tableColumns: [],
        dictKeys: [
          'upms_registered_client.authorization_grant_types',
          'upms_registered_client.autoapprove',
          'upms_registered_client.client_authentication_methods',
          'system.state'
        ]
      }
    },
    computed: {},
    methods: {
      buttonIcons,
      selectDictLabel,
      handleAdd() {
        this.$refs.applicationAddCom.handleOpen()
      },
      handleActions({ key, data }) {
        if (key === 'edit') {
          const parmas = {
            ...data
          }
          this.$refs.applicationAddCom.handleOpen(parmas)
        } else if (key === 'delete') {
          this.handleDeletePrompt(data.id)
        } else if (key === 'resetPwd') {
          this.$refs.applicationPwdCom.handleOpen(data)
        }
      },
      handleDeletePrompt(clientId) {
        this.$confirm(this.$t('system.application.deletePrompt'), this.$t('system.application.deleteTips'), {
          confirmButtonText: this.$t('common.sure'),
          cancelButtonText: this.$t('common.cancel')
        })
          .then((confirm) => {
            // const ids = clientId ? clientId : this.selectionRows.map((v) => v.id).join(',')
            this.handleDeleteClient(clientId)
          })
          .catch((cancel) => {})
      },
      async handleDeleteClient(clientId) {
        const formData = new FormData()
        formData.append('id', clientId)
        const { code, msg } = await apiPutDeleteClient(formData)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('common.deleteSuccess'))
        } else {
          this.$message.error(msg)
        }
        this.loadData()
      },
      async handleChangeState(state, ids) {
        const result = Array.isArray(ids) ? ids : [ids]

        try {
          const { code, msg } =
            `${state}` === '0' ? await apiPutEnableClient(result) : await apiPutDisableClient(result)
          if (code === EnumApiCode.Success) {
            this.$message.success(this.$t('system.application.successTips'))
          } else {
            this.$message.error(msg)
          }
          this.loadData()
        } finally {
          this.loadData()
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .clientImg {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    margin: auto;
  }
</style>
